<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<canvas width="500px" height="500px" id="canvas"></canvas>
	</body>
	<style>
		canvas {
			margin: 0 auto;
			border: 1px solid #000;
			display: block;
		}
	</style>
	<script>
		var canvas = document.querySelector('#canvas'); //获取画布
		var ctx = canvas.getContext('2d'); //获取画布上下文
		
		// 画布宽高
		let w=h=500
		
		var x = 100;
		var y = 100;
		var r = 20 ;
		let f=false
		let t=false
		let Xs=parseInt(Math.random()*10)
		let Ys=parseInt(Math.random()*10)
		function drawCircle(x,y,r){
			ctx.beginPath()
			ctx.arc(x,y,r,0,Math.PI*2)
			ctx.fillStyle='yellow';
			ctx.fill()
			ctx.stroke()
		}
		
		/* setInterval(function(){
			ctx.clearRect(0,0,w,h)
			if(f==false){
			x+=Xs
			}else{
				x-=Xs
			}
			if(t==false){
			y+=10
			}else{
				y-=10
			}
			drawCircle(x,y,r)
			if(x>=480){
				f=true
				Xs=Math.random()*10
				console.log(Xs);
			}else if(x<=20){
				f=false
				Xs=Math.random()*10
			}
			// y
			if(y>=480){
				t=true
			}else if(y<=20){
				t=false
			}
		},50) */
		//小球循环
		setInterval(function(){
			ctx.clearRect(0,0,w,h)
			if(x<=r||x>=w-r){
				Xs=-Xs
			}
			if(y<=r||y>=h-r){
				Ys=-Ys
			}
			x+=Xs
			y+=Ys
			drawCircle(x,y,r)
		},50)
		
		
	</script>
</html>